package web;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import command.LoginCommand;

public class LoginFilter implements Filter {
	private ServletContext servletContext;

	@Override
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException,
			ServletException {

		final HttpServletRequest req = (HttpServletRequest) request;
		final HttpServletResponse resp = (HttpServletResponse) response;

		if (!Boolean.TRUE.equals(req.getSession(true).getAttribute(LoginCommand.SESS_AUTH))
				&& !(req.getRequestURI().equals("/login.jspx")||req.getRequestURI().equals("/login.do")
						|| (req.getParameter("command")!= null  && req.getParameter("command").equals("login")))) {
			// resp.sendRedirect("login.html");
			// mime-type information collides with resource extension
			servletContext.getRequestDispatcher("/login.jspx").forward(req, resp);
			
			return;
			
		}

		chain.doFilter(request, response);

	}

	@Override
	public void init(FilterConfig filterConfig) throws ServletException {
		servletContext = filterConfig.getServletContext();
	}

	@Override
	public void destroy() {
		// nothing to do here
	}

}
